package com.bos.controller.json;

import com.bos.dao.AnggaranDAO;
import com.bos.dao.PeriodeDAO;
import com.bos.dao.SekolahDAO;
import com.bos.domain.Anggaran;
import com.bos.domain.Periode;
import com.bos.domain.Sekolah;
import com.bos.editor.AnggaranEditor;
import com.bos.editor.PeriodeEditor;
import com.bos.editor.SekolahEditor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: Latief
 * Date: 3/17/11
 * Time: 8:29 PM
 * To change this template use File | Settings | File Templates.
 */
@Controller
public class AnggaranJsonController {

    private AnggaranDAO anggaranDAO;
    private PeriodeDAO periodeDAO;
    private SekolahDAO sekolahDAO;

/* --------------------- Getter and Setter ---------------------*/

    @Autowired
    public void setAnggaranDAO(AnggaranDAO anggaranDAO) {
        this.anggaranDAO = anggaranDAO;
    }

    @Autowired
    public void setPeriodeDAO(PeriodeDAO periodeDAO) {
        this.periodeDAO = periodeDAO;
    }

    @Autowired
    public void setSekolahDAO(SekolahDAO sekolahDAO) {
        this.sekolahDAO = sekolahDAO;
    }

    /**
     * ************** JSON **************************************************************************
     */

    @RequestMapping(value = "/sekolah/{npsn}/anggaran.json", method = RequestMethod.GET)
    public
    @ResponseBody
    List<Anggaran> index(@PathVariable("npsn") Sekolah sekolah) {
        try {
            return anggaranDAO.getBySekolah(sekolah);
        } catch (DataAccessException e) {
            return new ArrayList<Anggaran>();
        }
    }

    @RequestMapping(value = "/sekolah/{npsn}/anggaran/periode/{periodeId}.json", method = RequestMethod.GET)
    public
    @ResponseBody
    Anggaran show(@PathVariable("npsn") Sekolah sekolah, @PathVariable("periodeId") Periode periode) {
        return anggaranDAO.getBySekolahPeriode(sekolah, periode);
    }

    @InitBinder
    protected void initBinder(WebDataBinder binder) throws Exception {
        binder.registerCustomEditor(Sekolah.class, new SekolahEditor(sekolahDAO));
        binder.registerCustomEditor(Periode.class, new PeriodeEditor(periodeDAO));
        binder.registerCustomEditor(Anggaran.class, new AnggaranEditor(anggaranDAO));
    }
}
